Skip to content

Fix: Prevent Connection Pollution by Closing/Resetting Connection on Context Cancellation During BeginTx - #13

Open
jamboriu wants to merge 4 commits into
raimeecas:mainfrom
jamboriu:fix/connection-pollution
Open

Fix: Prevent Connection Pollution by Closing/Resetting Connection on Context Cancellation During BeginTx#13
jamboriu wants to merge 4 commits into
raimeecas:mainfrom
jamboriu:fix/connection-pollution

Conversation

@jamboriu

@jamboriu jamboriu commented Aug 2, 2026

Copy link
Copy Markdown

Resolves #1

Description

This pull request prevents connection pollution in the database pool during transaction initialization (BeginTx).

When a transaction start (START TRANSACTION or setting transaction isolation level) is interrupted by context cancellation, the connection state becomes ambiguous and "dirty" (the server might have actually initiated the transaction, but the driver returns a context error to the client). If this connection is recycled back into the Go database/sql connection pool, subsequent queries will run inside an uncommitted, leaked transaction.

Solution

  1. Ambiguity Mitigation: Whenever context cancellation (ctx.Err() != nil) is detected immediately after executing isolation level configurations or START TRANSACTION command roundtrips, the driver explicitly closes the underlying net connection.
  2. Pool Eviction: Returns driver.ErrBadConn to the caller. This is the official signal to Go's database/sql connection pool to destroy the connection and evict it from the pool instead of recycling it.
  3. Resource Leak Prevention: Closed flag and lock guard ensure clean resource reclamation without race conditions.

Verification & Testing

Implemented comprehensive unit tests in connection_test.go:

  • TestBeginTxContextCancellation: Validates that cancellation during transaction start closes the net connection and returns driver.ErrBadConn.
  • TestBeginTxContextCancellationDuringIsolationSetting: Validates that cancellation during isolation level writes is handled safely.
  • TestBeginTxSuccess: Confirms normal transaction initiation flow when context is not canceled.
  • TestBeginTxAlreadyClosedConnection: Confirms error behavior on already closed driver connections.

All tests passed successfully on Go 1.23.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🎯 Prevent Connection Pollution by Closing/Resetting Connection on Context Cancellation During BeginTx

1 participant